package com.liuxin.zhiyuan.shujuzhongxin.controller;

import com.alibaba.fastjson.JSON;
import com.liuxin.common.utils.R;
import com.liuxin.zhiyuan.shujuzhongxin.domain.po.VolunteerRecommendationEntity;
import com.liuxin.zhiyuan.shujuzhongxin.domain.po.VolunteerRecommendationTempEntity;
import com.liuxin.zhiyuan.shujuzhongxin.service.MajorGroupScoreService;
import com.liuxin.zhiyuan.shujuzhongxin.service.VolunteerRecommendationService;
import com.liuxin.zhiyuan.shujuzhongxin.service.VolunteerRecommendationTempService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * 志愿填报推荐接口
 *
 * @author zsl
 * @email 1301966496@qq.com
 * @date 2025-11-08 22:16:26
 */

@RestController
@RequestMapping("shujuzhongxin/volunteer")
public class VolunteerRecommendationController {
    @Autowired
    private MajorGroupScoreService majorGroupScoreService;

    @Autowired
    private VolunteerRecommendationService volunteerRecommendationService;

    @Autowired
    private VolunteerRecommendationTempService volunteerRecommendationTempService;

    /**
     * 生成志愿填报推荐
     * 根据学生ID生成稳冲保志愿推荐
     * @param xueyuanid 学生ID（lxzy_xueyuan_info表的id字段）
     * @return 推荐结果JSON
     */
    //@GetMapping("/recommend")
    public R recommend(@RequestParam("xueyuanid") Integer xueyuanid) {
        try {
            Map<String, Object> recommendation = majorGroupScoreService.getVolunteerRecommendation(xueyuanid);
            if (recommendation.containsKey("error")) {
                return R.error(recommendation.get("error").toString());
            }
            String res = saveVolunteerRecommendation(recommendation, xueyuanid);
            if (StringUtils.isBlank(res)){
                return R.ok();
            }
            return R.error(res);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("志愿推荐服务异常：" + e.getMessage());
        }
    }

    /**
     * 生成志愿填报推荐（POST版本）
     */
    @PostMapping("/recommend")
    public R recommendPost(@RequestBody Map<String, Object> params) {
        try {
            String xueyuanids = params.get("xueyuanid").toString();
            if (xueyuanids == null) {
                return R.error("学生ID不能为空");
            }
            Integer xueyuanid = Integer.parseInt(xueyuanids);
            Map<String, Object> recommendation = majorGroupScoreService.getVolunteerRecommendation(xueyuanid);
            if (recommendation.containsKey("error")) {
                return R.error(recommendation.get("error").toString());
            }

            //保存结果到lxzy_Volunteer_recommendation_temp、lxzy_Volunteer_recommendation表
            String res = saveVolunteerRecommendation(recommendation, xueyuanid);
            if (StringUtils.isBlank(res)){
                return R.ok();
            }
            return R.error(res);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("志愿推荐服务异常：" + e.getMessage());
        }
    }


    public String saveVolunteerRecommendation(Map<String, Object> recommendation, Integer xueyuanid) {
        //保存结果到lxzy_Volunteer_recommendation表
        //判断是否存在该记录
        VolunteerRecommendationEntity existingRecord = volunteerRecommendationService.getByIdWithVersion(xueyuanid);
        if (existingRecord != null) {
            VolunteerRecommendationEntity record = new VolunteerRecommendationEntity();
            // 存在记录，更新版本号
            Integer newVersion = existingRecord.getVersion() + 1;
            record.setVersion(newVersion);
            record.setTiaojian("");
            String jsonString = JSON.toJSONString(recommendation);
            record.setJieguo(jsonString);
            record.setXueyuanId(xueyuanid);
            record.setCreateTime(new Date());
            volunteerRecommendationService.save(record);
            // 生成志愿填报记录存入lxzy_VolunteerRecommendation_temp表
            VolunteerRecommendationTempEntity tempRecord = new VolunteerRecommendationTempEntity();
            tempRecord.setVrId(record.getId());
            tempRecord.setXueyuanId(xueyuanid);
            tempRecord.setTiaojian("");
            tempRecord.setJieguo(jsonString);
            tempRecord.setCishu(1);
            tempRecord.setCreateTime(new Date());
            tempRecord.setUpdateTime(new Date());
            volunteerRecommendationTempService.save(tempRecord);
        }else{
            VolunteerRecommendationEntity record = new VolunteerRecommendationEntity();
            record.setXueyuanId(xueyuanid);
            record.setTiaojian("");
            String jsonString = JSON.toJSONString(recommendation);
            record.setJieguo(jsonString);
            record.setCreateTime(new Date());
            record.setVersion(1);
            volunteerRecommendationService.save(record);
            // 生成志愿填报记录存入lxzy_VolunteerRecommendation_temp表
            VolunteerRecommendationTempEntity tempRecord = new VolunteerRecommendationTempEntity();
            tempRecord.setVrId(record.getId());
            tempRecord.setXueyuanId(xueyuanid);
            tempRecord.setTiaojian("");
            tempRecord.setJieguo(jsonString);
            tempRecord.setCishu(1);
            tempRecord.setCreateTime(new Date());
            tempRecord.setUpdateTime(new Date());
            volunteerRecommendationTempService.save(tempRecord);
        }
        return "";
    }
}
